﻿using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Windows.Forms;

using Exif.Jpeg;
using Exif.Jpeg.Base;
using Exif.Jpeg.Enums;
using Exif.Jpeg.Segments;

namespace ExifTest
{
	public partial class StructureView : Form
	{
		public StructureView()
		{
			InitializeComponent();
		}

		private static List<SegmentBase> GetBlocks(string filePath)
		{
			var stream = File.OpenRead(filePath);
			var length = (int)stream.Length;
			var buffer = new byte[length];
			stream.Read(buffer, 0, length);

			var provider = new JpegImageProvider(buffer);
			var offset = 0;

			var blocks = new List<SegmentBase>();

			var block = JpegSegmentFactory.CreateSegment(provider, offset);
			blocks.Add(block);
			Debug.WriteLine(block.Marker);

			while (block.Marker != JpegMarker.EOI)
			{
				offset += 2 + block.Length;

				if (block.Marker == JpegMarker.SOS)
				{
					block = new SegmentImageData(provider, JpegMarker.ImageData, offset,
						(int)provider.ImageReader.Length - offset - 4);
				}
				else
				{
					block = JpegSegmentFactory.CreateSegment(provider, offset);
				}

				blocks.Add(block);
				Debug.WriteLine(block.Marker);
			}
			return blocks;
		}

		private void toolStripButton_Click(object sender, EventArgs e)
		{
			if (openFileDialog1.ShowDialog(this) == DialogResult.OK)
			{
				var file = openFileDialog1.FileName;
				bindingSource.DataSource = GetBlocks(file);
				listBox_SelectedIndexChanged(this, EventArgs.Empty);
			}
		}

		private void listBox_SelectedIndexChanged(object sender, EventArgs e)
		{
			var block = listBox.SelectedItem as SegmentBase;
			if(block != null)
			{
				propertyGrid.SelectedObject = block;
			}
		}
	}
}